package com.yunao.web.mail;

import static java.util.stream.Collectors.toList;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import com.yunao.commons.serachcore.core.bean.Article;
import com.yunao.service.template.MailTextInfo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;


@Component
@Slf4j
public class MailService {

    @Autowired
    JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void send(String subject, String to, String text) {
        send(subject, new String[] { to }, text);
    }

    public void send(String subject, String[] to, String text) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            if (from.contains("@") && from.contains(".")) {
                helper.setFrom(from);
            }
            helper.setSubject(subject);
            helper.setTo(to);
            helper.setText(text, true);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("send mail error", e);
        }
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    public String getMailTemplate(List<Article> articles) {
        Collections.sort(articles, Comparator.comparing(Article::getTitle).reversed());

        Context context = new Context();
        context.setVariable("alarm", createAlarmInfo(articles));
        return templateEngine.process("article.mail", context);
    }

    private MailTextInfo createAlarmInfo(List<Article> articles) {
        MailTextInfo alarmInfo = new MailTextInfo();
        alarmInfo.setSubject("云奥舆情");
        alarmInfo.setTime(DateTime.now().toString("yyyy-MM-dd HH:mm"));
        long negs = articles.stream().filter(article -> "负面".equals(article.getEmotion())).count();
        String statistics = "发送消息共 " + articles.size() + " 条，负面消息 " + negs + " 条。";
        alarmInfo.setStatistics(statistics);
        alarmInfo.setArticles(articles);
        alarmInfo.setCancel("http://ssl.esou.me/ab_cancel.do?p=$param");
        return alarmInfo;
    }

}
